package cn.yunyichina.provider.framework.recipe.util;

import java.awt.Color;    
import java.awt.Font;    
import java.awt.Graphics;    
import java.awt.image.BufferedImage;    
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;    
import java.util.HashMap;
import java.util.List;    
import java.util.Map;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import cn.yunyichina.provider.iface.entity.clinic.RecipeVo;
import cn.yunyichina.provider.iface.entity.clinic.RpItemVo;
import cn.yunyichina.utils.commons.StringUtils;

    
public class RecipePicUtil {     
	
	private static final Logger logger = LoggerFactory.getLogger(RecipePicUtil.class);
	/**  
     * 生成新图片到本地  
     */  
    public static void writeImageLocal(String newImage, BufferedImage img) {  
        if (newImage != null && img != null) {  
            try {  
                File outputfile = new File(newImage);  
                ImageIO.write(img, "jpg", outputfile);  
            } catch (IOException e) {  
                System.out.println(e.getMessage());  
            }  
        }  
    }  
	
	
    public static BufferedImage loadImageLocal(String imgName) {  
        try {  
            return ImageIO.read(new File(imgName));  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }  
        return null;  
    }  
  
   
    public static BufferedImage loadImageUrl(String imgName) {  
        try {  
            URL url = new URL(imgName);  
            return ImageIO.read(url);  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }  
        return null;  
    }  
    
    public static String createRecipe(RecipeVo recipe,String saveFilePath,String sealFilePath){
    	
    	String  fileName=null;
    	
    	logger.info("开始生成处方图片成功");
    	int imageWidth = 700;// 图片的宽度    
        int imageHeight = 1000;// 图片的高度    
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,    
                BufferedImage.TYPE_INT_RGB);    
        Graphics graphics = image.getGraphics();    
    	
    	try{
            graphics.setColor(Color.white);    
            graphics.fillRect(0, 0, imageWidth, imageHeight);    
            graphics.setColor(Color.black);    
        
            int high = 80;    
            graphics.setFont(new Font("黑体", Font.BOLD, 35));
            String hospitalName=recipe.getHospitalName();
            int hospitalXWidth=40+(17-hospitalName.length())*18;
            graphics.drawString(hospitalName, hospitalXWidth, high);//医院名字    
            graphics.setFont(new Font("黑体", Font.BOLD, 25));    
            high += 40;
            graphics.drawString("处方签", 310, high); 
            high += 20;
            //graphics.setFont(new Font("宋体", Font.BOLD, 18));    
            //graphics.drawString("处方编号：(西)"+recipe.getRecipeNum(), 420, high); //处方编号
            high += 10;
            graphics.drawLine(50, high, 680, high);
            
            //---------------------------------------------------
            graphics.setFont(new Font("宋体", Font.BOLD, 18));    
            high += 40;
            graphics.drawString("姓名：", 50, high);
            graphics.drawLine(100, high+5, 220, high+5);
            graphics.drawString("性别：", 250, high);
            graphics.drawLine(300, high+5, 420, high+5);
            graphics.drawString("年龄：", 450, high);
            graphics.drawLine(500, high+5, 620, high+5);
            //填值
            graphics.drawString(recipe.getName(), 120, high-5); //姓名
            graphics.drawString(recipe.getSex(), 320, high-5); //性别
            graphics.drawString(recipe.getAge(), 520, high-5); //性别
            
            //-----------------------------------------------------
            high += 40;
            graphics.drawString("就诊时间：", 50, high);
            graphics.drawLine(140, high+5, 320, high+5);
            graphics.drawString("就诊科室：", 360, high);
            graphics.drawLine(450, high+5, 620, high+5);
           
            //填值
            graphics.drawString(recipe.getVisitingTime(), 145, high-5);//就诊时间
            graphics.drawString(recipe.getDeptName(), 470, high-5);//科室
            
            //----------------------------------------------------------
            high += 40;
            graphics.drawString("门诊流水号：", 50, high);
            graphics.drawLine(160, high+5, 340, high+5);
            //填值
            graphics.drawString(recipe.getQueueNum(), 165, high-5);//就诊序列号

            graphics.drawString("就诊卡号：", 360, high);
            graphics.drawLine(450, high+5, 620, high+5);
            if(!StringUtils.isBlank(recipe.getMedicalCardNo())){
                //填值
                graphics.drawString(recipe.getMedicalCardNo(), 470, high-5);//就诊卡号
            }

            //----------------------------------------------------------
            graphics.setFont(new Font("黑体", Font.BOLD, 20)); 
            high += 30;
            graphics.drawLine(50, high, 680, high);
           
            graphics.setFont(new Font("黑体", Font.BOLD, 40)); 
            high += 50; 
            graphics.drawString("Rp：", 50, high);
            
            //-----------------------------RP-------------------------------------
            List<RpItemVo> items=recipe.getRpItems();

             for(int i=1;i<=items.size();i++){
            	 RpItemVo itemp=items.get(i-1);
            	 high += 30;
            	 graphics.setFont(new Font("宋体", Font.PLAIN, 18));
            	 graphics.drawString(itemp.getItemName(), 75, high);
            	 if(!StringUtils.isBlank(itemp.getItemUnit())){
                     high += 30;
                     graphics.setFont(new Font("宋体", Font.PLAIN, 18));
                     graphics.drawString(itemp.getItemUnit(), 100, high);
                 }
             }
             high += 40;
             graphics.setFont(new Font("宋体", Font.PLAIN, 20));
             graphics.drawString("(以下空白)", 80, high);
             
             //----------------------------底部开始--------------------------------
             graphics.setFont(new Font("黑体", Font.BOLD, 20)); 
             int lineBottomHigh=850;
             graphics.drawLine(50, lineBottomHigh, 680, lineBottomHigh);

             //--------------------------底部1--------------------------------------
             lineBottomHigh += 40;
             graphics.drawString("医师：", 50, lineBottomHigh);
             graphics.drawLine(100, lineBottomHigh+5, 230, lineBottomHigh+5);
             graphics.drawString("金额：", 260, lineBottomHigh);
             graphics.drawLine(310, lineBottomHigh+5, 440, lineBottomHigh+5);
             
             
             //填值
             graphics.setFont(new Font("宋体", Font.BOLD, 20)); 
             graphics.drawString(recipe.getDoctorName(), 120, lineBottomHigh-5); //医生姓名
             graphics.drawString(recipe.getTotalMoney(), 320, lineBottomHigh-5); //金额
             //---------------------------------------------------------------------
             
             //--------------------------底部2--------------------------------------
             lineBottomHigh += 40;
             graphics.drawString("审核药师：", 50, lineBottomHigh);
             graphics.drawLine(150, lineBottomHigh+5, 250, lineBottomHigh+5);
             graphics.drawString("调配药师：", 270, lineBottomHigh);
             graphics.drawLine(370, lineBottomHigh+5, 470, lineBottomHigh+5);
             graphics.drawString("核发药师：", 490, lineBottomHigh);
             graphics.drawLine(590, lineBottomHigh+5, 680, lineBottomHigh+5);
             //---------------------------------------------------------------------
             
             //合并图片
             if(!StringUtils.isEmpty(sealFilePath)){
                 BufferedImage d = loadImageLocal(sealFilePath);  //盖章
                 graphics.drawImage(d, 500, lineBottomHigh-130, 180, 80, null);  
             }
             
             writeImageLocal(saveFilePath, image);
             logger.info("生成处方图片成功:"+saveFilePath);
             fileName=uploadQiNiu(saveFilePath);
    	}catch(Exception ex){
    		fileName=null;
    		logger.error("生成处方图片异常:"+ex.getMessage(),ex);
    	}finally{
    		if(graphics!=null){
    			 graphics.dispose();
    		}
    	}
    	
    	return fileName;
    
    }
    
    public static String uploadQiNiu(String saveFilePath){
    	String url=null;
    	String ACCESS_KEY = "6MpX59besahQ1TEFbRRd0hGEr8Alf1OMWP9Vr9Pp";
        String SECRET_KEY = "q3i6AXH6m8qmMJwnwTdVG9h9Y0pozcD6-oQTM0Px";
        String bucketname = "recipe";
        String domain="http://olg7n4itc.bkt.clouddn.com/";
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //创建上传对象华东  Zone.zone0() 华北  Zone.zone1() 华南  Zone.zone2() 北美  Zone.zoneNa0()
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager=new UploadManager(cfg);
        try {
			Response res=uploadManager.put(saveFilePath, null, auth.uploadToken(bucketname));
			logger.info("七牛返回："+res.bodyString());
			if (res.isOK()) {
                Map<String, String> bodyMap = JSON.parseObject(res.bodyString(),Map.class);
                url= domain + bodyMap.get("hash");
	        } 
		} catch (QiniuException e) {
			e.printStackTrace();
			logger.error("七牛图片上传异常",e);
		}
        return url;
    }
    
    public static void main(String[] args){    
    	RecipeVo r=new RecipeVo();
    	
    	List<RpItemVo> items=new ArrayList<RpItemVo>();
    	items.add(new RpItemVo("咽炎片    1盒","口服 3次/日 每次两片,共3日"));
        items.add(new RpItemVo("阿西莫林 1盒","口服 3次/日 每次1粒 共3日"));
        r.setRpItems(items);
        r.setHospitalName("广州中医药大学第一附属医院");
        r.setAge("32");
        r.setDeptName("免疫科");
        r.setDoctorName("饶仕宝");
        r.setName("张三");
        r.setQueueNum("1111333");
        r.setRecipeNum("66882342349123");
        r.setSex("男");
        r.setTotalMoney("987.56");
        r.setVisitingTime("2017-02-15 12:34:56");
        String sealFilePath="D://1.png";
        String saveFilePath="D://test1.jpg";
        createRecipe(r,saveFilePath,sealFilePath);
    }  
    
}    